import { useEffect, useRef, useState } from "react";
import { PageContainer } from "@ant-design/pro-layout";
import useCommonTable from "@/hooks/useCommonTable";
import { fetchInfo } from "@/api/class";

import {
  classStatusOptions,
  filterCourseTypeOptions,
  filterTopic,
  calcWeekDay,
} from "@/const";
import courseTypeOptions from "@/courseTypeOptions";

import {
  ProFormText,
  ProFormRadio,
  ProFormCascader,
  ProFormDigit,
  ProFormTextArea,
  ProFormSelect,
  ProFormTimePicker,
  ProFormDatePicker,
  ModalForm,
  ProFormList,
  ProFormGroup,
  ProFormDependency,
} from "@ant-design/pro-form";
import moment from "moment";
import { Button, Row, Col, Tag, Card, message } from "antd";
import { fetchList as fetchTeacherList } from "@/api/teacher";
import { fetchList as fetchRoomList } from "@/api/room";
import { fetchList, update, add, remove } from "@/api/classRecord";
import {
  add as addStudentClassRecord,
  update as updateStudentClassRecord,
} from "@/api/studentClassRecord";

import { history, useLocation } from "umi";
import { ArrowLeftOutlined } from "@ant-design/icons";

export default () => {
  const actionRef = useRef();
  const formRecordRef = useRef();
  const [teacherList, setTeacherList] = useState([]);
  const [roomList, setRoomList] = useState([]);
  const [classInfo, setClassInfo] = useState({});
  const { id } = useLocation().query;

  const getTeacherList = async () => {
    const res = await fetchTeacherList({
      page: 1,
      pageSize: 100,
    });
    setTeacherList(res.data);
  };

  const getRoomList = async () => {
    const res = await fetchRoomList({
      page: 1,
      pageSize: 100,
    });
    setRoomList(res.data);
  };

  const getClassInfo = async () => {
    const res = await fetchInfo({ id });
    if (res.data) {
      setClassInfo(res.data);
    }
  };

  useEffect(() => {
    getTeacherList();
    getRoomList();
    getClassInfo();
  }, []);

  const columns = [
    {
      title: "教师",
      dataIndex: "teacherId",
      valueType: "select",
      fieldProps: {
        options: teacherList,
        fieldNames: {
          label: "name",
          value: "_id",
        },
      },
      render: (_, record) => {
        return record.teacher.name;
      },
    },

    {
      title: "上课日期",
      dataIndex: "classDate",
      width: 240,
      render: (_, record) => {
        return `${record.classDate} ${calcWeekDay(record.classDate)} ${
          record.classTimeStart
        }-${record.classTimeEnd}`;
      },
      search: false,
    },
    {
      title: "课程阶段",
      dataIndex: "topic",
      valueType: "select",
      render: (_, record) => {
        return filterCourseTypeOptions(record.topic[0]);
      },
    },
    {
      title: "课程主题",
      dataIndex: "topic",
      valueType: "select",
      render: (_, record) => {
        const studentClassRecordList = record.studentClassRecordList;
        // 如果存在上课记录，就从上课记录里面取，否则取排课记录的
        if (studentClassRecordList.length) {
          const firstObj = studentClassRecordList[0];
          return firstObj.topicType == 1
            ? filterTopic(firstObj.topic)
            : firstObj.topicCustom;
        } else {
          return filterTopic(record.topic);
        }
      },
    },

    {
      title: "出勤率",
      dataIndex: "lessonConsumption",
      search: false,
      render: (_, record) => {
        const studentLength = record.studentList.length;
        const okLength = record.studentClassRecordList?.filter(
          (item) => item.isDeduct
        );
        return (
          <>
            <span style={{ color: "red" }}>
              {okLength.length}/{studentLength}
            </span>
          </>
        );
      },
    },
    {
      title: "上课学生",
      dataIndex: "studentList",
      width: 200,
      render: (_, record) => {
        return record?.studentList?.map((item) => (
          <Tag
            style={{ marginTop: 10 }}
            color={item.gender === 1 ? "blue" : "magenta"}
          >
            {item.name}
          </Tag>
        ));
      },
    },
  ];
  const renderFormItem = ({ record, type, formRef }) => {
    return (
      <>
        <Row gutter={20}>
          <Col span={12}>
            <ProFormText
              label="教室id"
              name="classId"
              hidden
              initialValue={id}
            />
            <ProFormText
              label="学生id"
              name="studentIds"
              hidden
              initialValue={record?.studentIds || classInfo?.studentIds}
            />

            <ProFormDatePicker
              width="lg"
              label="上课日期"
              name="classDate"
              placeholder={"请选择上课日期"}
              fieldProps={{
                format: "YYYY/MM/DD",
              }}
              initialValue={moment()}
              rules={[
                {
                  required: true,
                  message: "请选择上课日期",
                },
              ]}
            />
          </Col>
          <Col span={12}>
            <ProFormTimePicker.RangePicker
              width="lg"
              label="上课时间"
              name="time"
              placeholder={["开始时间", "结束时间"]}
              fieldProps={{
                format: "HH:mm",
              }}
              initialValue={[classInfo.classTimeStart, classInfo.classTimeEnd]}
              transform={(values) => {
                return {
                  classTimeStart: values ? values[0] : undefined,
                  classTimeEnd: values ? values[1] : undefined,
                };
              }}
              rules={[
                {
                  required: true,
                  message: "请选择时间段",
                },
              ]}
            />
          </Col>
        </Row>

        <Row gutter={20}>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="teacherId"
              label="教师"
              allowClear
              fieldProps={{
                options: teacherList,
                fieldNames: {
                  label: "name",
                  value: "_id",
                },
              }}
              initialValue={classInfo.teacherId}
              rules={[{ required: true, message: "请选择教师" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormDigit
              width="lg"
              label="学生消耗课时"
              name="lessonConsumption"
              placeholder="请输入学生消耗课时"
              addonAfter="课时"
              fieldProps={{
                precision: 1,
              }}
              initialValue={classInfo.lessonConsumption}
              rules={[{ required: true, message: "请输入学生消耗课时" }]}
            />
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={12}>
            <ProFormSelect
              width="lg"
              name="roomId"
              label="教室"
              allowClear
              fieldProps={{
                options: roomList,
                fieldNames: {
                  label: "name",
                  value: "_id",
                },
              }}
              initialValue={classInfo.roomId}
              rules={[{ required: true, message: "请选择教室" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormCascader
              width="lg"
              name="topic"
              label="课程主题"
              fieldProps={{
                options: courseTypeOptions,
                showSearch: true,
                filter: (inputValue, path) =>
                  path.some(
                    (option) =>
                      option.label
                        .toLowerCase()
                        .indexOf(inputValue.toLowerCase()) > -1
                  ),
              }}
              rules={[{ required: true, message: "请选择课程主题" }]}
            ></ProFormCascader>
          </Col>
        </Row>

        <Row gutter={20}>
          <Col span={12}>
            <ProFormTextArea
              width="lg"
              fieldProps={{
                rows: 5,
              }}
              name="remark"
              label="备注"
              placeholder="请输入备注"
            />
          </Col>
        </Row>
      </>
    );
  };

  // 记录上课
  const renderRecordAttendClassModal = (record, actionRef) => {
    let studentClassRecord = [];
    let totalInitialValues = {
      topicType: record.topicType || 1, // 本次课程主题
      topic: record.topic,
      remark: "",
    };
    const isUpdate = record.studentClassRecordList?.length;
    if (isUpdate) {
      totalInitialValues.topicType = record.studentClassRecordList[0].topicType;
      totalInitialValues.topic = record.studentClassRecordList[0].topic;
      totalInitialValues.topicCustom =
        record.studentClassRecordList[0].topicCustom;
      totalInitialValues.remark = record.studentClassRecordList[0].remark;
      studentClassRecord = record.studentClassRecordList.map((item) => {
        return {
          ...item,
          classHour:
            item.isDeduct == 1
              ? item.remainingClassHours + item.lessonConsumption
              : item.remainingClassHours,
        };
      });
    } else {
      studentClassRecord = record.studentList.map((item) => {
        const obj = {
          ...item,
          studentName: item.name,
          studentId: item._id,
          lessonConsumption: record.lessonConsumption, // 取排课记录设置的课时
          classStatus: 1, // 默认全部为上课
        };
        delete obj._id;
        return obj;
      });
    }
    formRecordRef.current?.setFieldsValue({
      studentClassRecord,
    });
    return (
      <ModalForm
        formRef={formRecordRef}
        key="record"
        title="记上课"
        width={"60%"}
        trigger={
          record.studentClassRecordList?.length ? (
            <Button type="dashed" danger>
              已记课
            </Button>
          ) : (
            <Button type="primary">记上课</Button>
          )
        }
        initialValues={{ ...totalInitialValues }}
        onFinish={async (values) => {
          console.log("values===", values);
          const list = [];
          values.studentClassRecord.forEach((item) => {
            let remainingClassHours = 0;
            let isDeduct = 0;
            // 如果上课状态选的是：上课 那么remainingClassHours = 总课时- 本节课需要消耗的课时
            if (item.classStatus === 1) {
              remainingClassHours = item.classHour - item.lessonConsumption;
              isDeduct = 1; // 上课，则设置为已扣除
            }
            // 如果上课状态选的是：请假 那么remainingClassHours = 总课时 本节课需要消耗的课时=0
            if (item.classStatus === 2) {
              remainingClassHours = item.classHour;
              item.lessonConsumption = 0;
              isDeduct = 0; // 请假，则设置为未扣除
            }
            list.push({
              studentClassRecordId: item._id, // 当前记上课记录id，修改的时候才有
              classRecordId: record._id, // 排课记录id
              studentId: item.studentId, // 学生id
              studentName: item.studentName, // 学生姓名
              classId: record.classId, // 班级id
              teacherId: record.teacherId, // 老师id
              roomId: record.roomId, // 教室id
              remainingClassHours, // 记课后还剩余多少课时
              classStatus: item.classStatus, //上课状态：1=上课 2=请假 3=补课
              lessonConsumption: item.lessonConsumption, // 本节课：消耗多少课时
              topicType: values.topicType, // 本次课程主题 1=系统选择 2=自定义
              topic: values.topicType === 1 ? values.topic : record.topic, // 系统选择
              topicCustom: values.topicCustom || "", // 自定义
              classDateStr: `${record.classDate} ${calcWeekDay(
                record.classDate
              )} ${record.classTimeStart}-${record.classTimeEnd}`, // 上课日期 2025/02/09 周六 08:30-10:00 格式
              isDeduct, // 当前记录是否扣除lessonConsumption课时 1=已扣除 0=未扣除
              remark: values.remark,
            });
          });
          const func = isUpdate
            ? updateStudentClassRecord
            : addStudentClassRecord;
          const res = await func({
            id: isUpdate ? 1 : "",
            list,
          });
          if (res.code == 0) {
            message.success(res.msg);
            actionRef?.current.reload();
            return true;
          }
        }}
      >
        <ProFormList
          name="studentClassRecord"
          initialValue={studentClassRecord}
          creatorButtonProps={false}
          actionRender={() => []}
        >
          <ProFormGroup key="group">
            <ProFormText label="_id" name="_id" hidden />
            <ProFormText label="姓名" name="studentName" disabled />
            <ProFormText label="剩余课时" name="classHour" disabled />

            <ProFormRadio.Group
              label="操作"
              name="classStatus"
              options={classStatusOptions}
            />
            <ProFormDependency name={["classStatus"]}>
              {({ classStatus }) => {
                return (
                  classStatus != 2 && (
                    <ProFormDigit
                      label="消耗课时"
                      name="lessonConsumption"
                      placeholder="请输入消耗课时"
                      fieldProps={{
                        precision: 1,
                      }}
                      rules={[{ required: true, message: "请输入消耗课时" }]}
                    />
                  )
                );
              }}
            </ProFormDependency>
          </ProFormGroup>
        </ProFormList>

        <Row>
          <Col span={12}>
            <ProFormRadio.Group
              label="本次课程主题"
              name="topicType"
              options={[
                {
                  value: 1,
                  label: "系统选择",
                },
                {
                  value: 2,
                  label: "自定义",
                },
              ]}
              rules={[{ required: true, message: "请选择" }]}
            />
          </Col>
          <Col span={12}>
            <ProFormDependency name={["topicType"]}>
              {({ topicType }) => {
                return topicType === 1 ? (
                  <ProFormCascader
                    width="lg"
                    name="topic"
                    label="系统选择"
                    fieldProps={{
                      options: courseTypeOptions,
                    }}
                    rules={[{ required: true, message: "请选择课程主题" }]}
                  ></ProFormCascader>
                ) : (
                  <ProFormText
                    label="自定义"
                    name="topicCustom"
                    rules={[{ required: true, message: "请输入课程主题" }]}
                  />
                );
              }}
            </ProFormDependency>
          </Col>
        </Row>

        <ProFormTextArea
          width="lg"
          fieldProps={{
            rows: 5,
          }}
          name="remark"
          label="备注"
          placeholder="请输入备注"
        />
      </ModalForm>
    );
  };
  return (
    <PageContainer
      extra={
        <Button onClick={() => history.goBack()}>
          <ArrowLeftOutlined />
          返回
        </Button>
      }
    >
      <Card title="当前班级学生">
        {classInfo?.studentList?.map((item) => (
          <Tag
            style={{ marginTop: 10 }}
            color={item.gender === 1 ? "blue" : "magenta"}
          >
            {item.name}
          </Tag>
        ))}
      </Card>

      {useCommonTable({
        actionRef,
        title: "排课",
        renderFormItem,
        search: false,
        columns,
        modalWidth: "50%",
        fetchList: async (params) => {
          const res = await fetchList({
            ...params,
            classId: id,
          });
          res.data = res.data.map((item) => {
            return {
              ...item,
              time: [item.classTimeStart, item.classTimeEnd],
            };
          });

          return res;
        },
        add,
        update,
        remove,
        insertPosition: 3,

        renderOtherAction: (_, record, actionRef) => {
          return renderRecordAttendClassModal(record, actionRef);
        },
        actionColumnWidth: 200,
        showCheckbox: false,
      })}
    </PageContainer>
  );
};
